import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Box, Text, useInput } from 'ink';
import { Message, AppConfig, ConnectionStatus, ThemeConfig, ToolCall, ToolResult } from '../types';
import MessageList from './MessageList';
import InputArea from './InputArea';
import Header from './Header';
import StatusBar from './StatusBar';
import ToolUsageIndicator from './ToolUsageIndicator';
import { aiService } from '../services/ai';
import { interruptController } from '../services/interruptController';
import { BufferedOutputUpdater } from '../utils/bufferedUpdater';

interface ChatInterfaceProps {
  messages: Message[];
  config: AppConfig | null;
  connectionStatus: ConnectionStatus;
  theme: ThemeConfig;
  onAddMessage: (message: Omit<Message, 'id' | 'timestamp'>) => string;
  onUpdateMessage: (id: string, updates: Partial<Message>) => void;
  onClearMessages: () => void;
  autoQuestion?: string;
}

const ChatInterface: React.FC<ChatInterfaceProps> = ({
  messages,
  config,
  connectionStatus,
  theme,
  onAddMessage,
  onUpdateMessage,
  onClearMessages,
  autoQuestion
}) => {
  const [currentInput, setCurrentInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [autoQuestionSent, setAutoQuestionSent] = useState(false);
  const [interruptMessage, setInterruptMessage] = useState<string | null>(null);
  const bufferedUpdaterRef = useRef<BufferedOutputUpdater | null>(null);

  // 创建缓冲更新器的回调函数
  const createBufferedCallback = useCallback((messageId: string) => {
    return (content: string, isThinking?: boolean, thinkingContent?: string, toolCalls?: ToolCall[], toolResults?: ToolResult[]) => {
      const updates: Partial<Message> = {
        status: 'sending'
      };
      
      if (isThinking) {
        updates.isThinking = true;
        updates.thinkingContent = thinkingContent || '';
        updates.content = '';
      } else {
        updates.isThinking = false;
        updates.content = content;
        if (thinkingContent) {
          updates.thinkingContent = thinkingContent;
        }
        if (toolCalls) {
          updates.toolCalls = toolCalls;
        }
        if (toolResults) {
          updates.toolResults = toolResults;
        }
      }
      
      onUpdateMessage(messageId, updates);
    };
  }, [onUpdateMessage]);

  // 监听中断状态变化
  useEffect(() => {
    const unsubscribe = interruptController.onStatusChange((status) => {
      if (status.isInterrupting) {
        setInterruptMessage('⏹️ 操作已中断');
        setTimeout(() => setInterruptMessage(null), 2000);
      }
    });
    
    return unsubscribe;
  }, []);

  // 自动发送问题
  useEffect(() => {
    const sendAutoQuestion = async () => {
      if (!autoQuestion || autoQuestionSent || !config || !connectionStatus.connected) {
        return;
      }
      
      setAutoQuestionSent(true);
      
      const userMessageId = onAddMessage({
        role: 'user',
        content: autoQuestion.trim(),
        status: 'sent'
      });

      const aiMessageId = onAddMessage({
        role: 'assistant',
        content: '',
        status: 'sending'
      });

      setIsLoading(true);

      try {
        const bufferedCallback = createBufferedCallback(aiMessageId);
        bufferedUpdaterRef.current = new BufferedOutputUpdater(bufferedCallback);
        
        await aiService.sendMessage(
          autoQuestion,
          messages,
          config,
          (chunk: string, isThinking?: boolean, thinkingContent?: string, toolCalls?: ToolCall[], toolResults?: ToolResult[]) => {
            if (bufferedUpdaterRef.current) {
              bufferedUpdaterRef.current.addContent(chunk, isThinking, thinkingContent, toolCalls, toolResults);
            }
          }
        );

        if (bufferedUpdaterRef.current) {
          bufferedUpdaterRef.current.finalFlush();
          bufferedUpdaterRef.current.cleanup();
          bufferedUpdaterRef.current = null;
        }

        onUpdateMessage(aiMessageId, { status: 'sent' });
      } catch (error) {
        if (bufferedUpdaterRef.current) {
          bufferedUpdaterRef.current.cleanup();
          bufferedUpdaterRef.current = null;
        }
        
        if (error instanceof Error && error.name === 'AbortError') {
          onUpdateMessage(aiMessageId, {
            content: '操作已中断',
            status: 'interrupted'
          });
        } else {
          onUpdateMessage(aiMessageId, {
            content: `错误: ${error instanceof Error ? error.message : '未知错误'}`,
            status: 'error'
          });
        }
      } finally {
        if (bufferedUpdaterRef.current) {
          bufferedUpdaterRef.current.cleanup();
          bufferedUpdaterRef.current = null;
        }
        setIsLoading(false);
      }
    };
    
    sendAutoQuestion();
  }, [autoQuestion, autoQuestionSent, config, connectionStatus.connected, messages, onAddMessage, onUpdateMessage, createBufferedCallback]);

  useInput((input, key) => {
    if (key.escape) {
      interruptController.interrupt('用户按下ESC键中断');
      return;
    }
    
    if (key.ctrl && input === 'c') {
      process.exit(0);
    }
    
    if (key.ctrl && input === 'l') {
      onClearMessages();
    }
  });

  const handleSendMessage = useCallback(async (message: string) => {
    if (!message.trim() || !config) return;

    const userMessageId = onAddMessage({
      role: 'user',
      content: message.trim(),
      status: 'sent'
    });

    const aiMessageId = onAddMessage({
      role: 'assistant',
      content: '',
      status: 'sending'
    });

    setIsLoading(true);
    setCurrentInput('');

    try {
      const bufferedCallback = createBufferedCallback(aiMessageId);
      bufferedUpdaterRef.current = new BufferedOutputUpdater(bufferedCallback);
      
      await aiService.sendMessage(
        message,
        messages,
        config,
        (chunk: string, isThinking?: boolean, thinkingContent?: string, toolCalls?: ToolCall[], toolResults?: ToolResult[]) => {
          if (bufferedUpdaterRef.current) {
            bufferedUpdaterRef.current.addContent(chunk, isThinking, thinkingContent, toolCalls, toolResults);
          }
        }
      );

      if (bufferedUpdaterRef.current) {
        bufferedUpdaterRef.current.finalFlush();
        bufferedUpdaterRef.current.cleanup();
        bufferedUpdaterRef.current = null;
      }

      onUpdateMessage(aiMessageId, { status: 'sent' });
    } catch (error) {
      if (bufferedUpdaterRef.current) {
        bufferedUpdaterRef.current.cleanup();
        bufferedUpdaterRef.current = null;
      }
      
      if (error instanceof Error && error.name === 'AbortError') {
        onUpdateMessage(aiMessageId, {
          content: '操作已中断',
          status: 'interrupted'
        });
      } else {
        onUpdateMessage(aiMessageId, {
          content: `错误: ${error instanceof Error ? error.message : '未知错误'}`,
          status: 'error'
        });
      }
    } finally {
      if (bufferedUpdaterRef.current) {
        bufferedUpdaterRef.current.cleanup();
        bufferedUpdaterRef.current = null;
      }
      setIsLoading(false);
    }
  }, [config, messages, onAddMessage, onUpdateMessage, createBufferedCallback]);

  return (
    <Box flexDirection="column" height="100%">
      <Header config={config} theme={theme} />
      
      <Box flexGrow={1} flexDirection="column">
        <ToolUsageIndicator theme={theme} />
        <MessageList 
          messages={messages} 
          theme={theme}
        />
      </Box>

      <Box flexDirection="column">
        {interruptMessage && (
          <Box justifyContent="center" marginBottom={1}>
            <Text color="yellow">{interruptMessage}</Text>
          </Box>
        )}
        
        <Box>
          <Text color="gray">{'─'.repeat(80)}</Text>
        </Box>
        
        <InputArea
          value={currentInput}
          onChange={setCurrentInput}
          onSubmit={handleSendMessage}
          disabled={isLoading || !connectionStatus.connected}
          theme={theme}
        />
        
        <StatusBar
          connectionStatus={connectionStatus}
          isLoading={isLoading}
          theme={theme}
          interruptStatus={interruptController.getStatus()}
        />
      </Box>
    </Box>
  );
};

export default ChatInterface;